const app = getApp();
const db = wx.cloud.database();
const _ = db.command;
let localStatData = wx.getStorageSync("localStatData");
const key = app.globalData.key;

Page({
  data: {
    hasLoggedIn: true,
    userInfo: {},
    // statData:{
    //   _id: '',
    //   visitors_today:0,
    //   visitors_total:0,
    //   customers:0,
    //   msg_today:0,
    //   userId: '',
    //   timestamp: 0
    // },
    statData: {},
    weatherData: {},
    personal: {}
  },
  onLoad() {
    let that = this;
    let localStatData = wx.getStorageSync("localStatData");

    let LocalUserInfo = wx.getStorageSync("localUserInfo");
    let userId = wx.getStorageSync("userId");
    // console.log(JSON.stringify(Date.now()));
    console.log(JSON.stringify(LocalUserInfo.creatTime));
    console.log(JSON.stringify(LocalUserInfo.time));
    let currentTime = Date.now();
    // console.log("userId:" + wx.getStorageSync('userId'));
    // LocalUserInfo.userId = wx.getStorageSync('userId');

    wx.getLocation({
      success: (res) => {
        that.getWeather(`${res.longitude},${res.latitude}`)
      },
      fail: (res) => {
        this.fail(res)
      }
    })

  this.getHelloWorld();

    app.callbacks.push((userInfo) => {
      this.setData({
        userInfo: userInfo,
      });
    });

    // let LocalStatData = wx.getStorageSync('localStatData');

    app.callbacks.push((userInfo) => {

      if (!localStatData || !localStatData.refreshTime || currentTime - localStatData.refreshTime > 1000 * 3600) {
        // getStatData(db, userInfo.userId);
        db.collection("statistics-first-page")
          .where({
            userId: userInfo.userId,
          })
          .limit(1)
          .get({
            success: function (res) {
              if (res && res.data && res.data.length) {
                console.log("response data:" + JSON.stringify(res.data[0]));
                console.log("response data:" + res.data[0]);
                that.setData({
                  statData: res.data[0],
                });
                localStatData = res.data[0];
                localStatData.refreshTime = Date.now();
                wx.setStorageSync("localStatData", localStatData);
                resolve(res);
              }
            },
            fail: function (event) {
              console.error(event);
              reject(event);
            },
          });
      }else{
        that.setData({
          statData: localStatData
        })
      }
    });

    app.callbacks.push((userInfo) => {
      that.selectComponent("#card-default").getCardDetail();
    });
    // console.log("...........");
    // console.log("index:" + JSON.stringify(this.data.userInfo));
    // console.log("index:" + JSON.stringify(getApp().globalData.cardInfo));
    // console.log(JSON.stringify(app.callbacks.pop()));
  },
  getWeather(location){
    wx.request({
      url: `${app.globalData.requestUrl.weather}`,
      data: {
        location,
        key,
      },
      success: (res) => {
        if(res.statusCode === 200) {
          let data = res.data.HeWeather6[0]
          if(data.status === 'ok'){
            this.setData({
              weatherData: data
            })
          } else {
            wx.showToast({
              title: '查询天气失败',
              icon: 'none'
            })
          }
        }
      },
      fail: () => {
        wx.showToast({
          title: '查询天气失败',
          icon: 'none'
        })
      }
    })
  },
  getHelloWorld(){
    wx.request({
      url: `${app.globalData.requestUrl.helloworld}`,
      success: (res) => {
        if(res.statusCode == 200){
          console.log(JSON.stringify(res.data));
        }
      },
      fail: () => {
        wx.showToast({
          title: '接口调用失败',
          icon: 'none'
        })
      }
    })
  },
  onShow(e) {
    let currentTime = Date.now();
    let userId = app.globalData.userInfo.userId;
    if (!localStatData || !localStatData.refreshTime || currentTime - this.data.statData.refreshTime > 1000 * 30) {
      // getStatData(db, userId);
    }
    console.log(JSON.stringify(app.globalData.userInfo));
  },
  toSearch(e) {},
  toDetail(e) {
    wx.navigateTo({
      url: "../card-detail/card-detail",
    });
  },
  toEdit(e) {
    wx.navigateTo({
      url: "../edit-main/edit-main",
    });
  },
  toShare(e) {
    wx.navigateTo({
      url: "../share-main/share-main",
    });
  },
  scanCode(e) {
    wx.scanCode({
      success(res) {
        console.log(res);
      },
    });
  },
  mpAlert(e) {
    wx.showToast({
      title: "Coming soon ...",
      icon: "success",
      duration: 2000,
    });
  },
});

let getStatData = (db, currentUserId) => {
  let that = this;
  return new Promise((resolve, reject) => {
    db.collection("statistics-first-page")
      .where({
        userId: currentUserId,
      })
      .limit(1)
      .get({
        success: function (res) {
          if (res && res.data && res.data.length) {
            console.log("response data:" + JSON.stringify(res.data[0]));
            console.log("response data:" + res.data[0]);
            that.setData({
              statData: res.data[0],
            });
            localStatData.refreshTime = Date.now();
            sswx.setStorageSync("localStatData", this.data.statData);
            resolve(res);
          }
        },
        fail: function (event) {
          console.error(event);
          reject(event);
        },
      });
  });
};
// function getStatData(db, currentUserId){
//   console.log("userId:" + currentUserId);
//   db.collection("statistics-first-page")
//       .where({
//         userId: currentUserId,
//       })
//       .limit(1)
//       .get({
//         success:function(res){
//           if(res&&res.data&&res.data.length){
//             console.log("response data:" + JSON.stringify(res.data[0]));
//             this.setData({
//               statData:res.data[0]
//             });
//             wx.setStorageSync('localStatData', this.data.statData);
//           }
//         },
//         fail:function(event){
//           console.error(event);
//         }
//       });
// }
